//
// Created by 29491 on 2025/2/4.
//

#include "Time_load.h"

char timeStr[20];

Time_load currentTime;

void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
	// 将时间信息格式化为字符串
	sprintf(timeStr, "%04d-%02d-%02d %02d:%02d:%02d", currentTime.year, currentTime.month, currentTime.day,
			currentTime.hour, currentTime.minute, currentTime.second);

	LCD_SetWindows(TIME_X,TIME_Y,TIME_X+152,TIME_Y+16);//清除上次的时间
	for( uint16_t j=0;j<2432;j++)
	{
		LCD->LCD_RAM = WHITE;
	}

	// 调用 Show_Str 函数显示时间
	Show_Str(TIME_X, TIME_Y, BLUE, YELLOW, (uint8_t *)timeStr, 16, 1);

	// 更新时间
	updateTime(&currentTime);
}

//每个月的天数
int days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

// 初始化时间信息
void initTime(Time_load *time)
{
    time->year = 2025;
    time->month = 2;
    time->day = 6;
    time->hour = 11;
    time->minute = 55;
    time->second = 50;
}

// 判断是否为闰年
int isLeapYear(int year)
{
    return ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0));
}

// 获取每个月的天数
int getDaysInMonth(int year, int month)
{
    if (month == 2 && isLeapYear(year))
    {
        return 29;
    }
    return days[month - 1];
}

// 更新时间信息
void updateTime(Time_load *time)
{
    HAL_GPIO_TogglePin(GPIOC,GPIO_PIN_13);
    time->second++;
    if (time->second >= 60)
    {
        time->second = 0;
        time->minute++;
        if (time->minute >= 60)
        {
            time->minute = 0;
            time->hour++;
            if (time->hour >= 24)
            {
                time->hour = 0;
                time->day++;
                if (time->day > getDaysInMonth(time->year, time->month))
                {
                    time->day = 1;
                    time->month++;
                    if (time->month > 12)
                    {
                        time->month = 1;
                        time->year++;
                    }
                }
            }
        }
    }
}


void TIME_Init(void)
{
	HAL_TIM_Base_Start_IT(&htim1);
    initTime(&currentTime);
}

